import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/useUserStore'
// 创建 axios 实例
const service = axios.create({
  baseURL: '/api',
  timeout: 15000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    //获取token
    const userStore = useUserStore()
    const token = userStore.token;
    if (token) {
      config.headers['Authorization'] = `${token}`
    }
    return config
  },
  error => {
    console.error('请求错误：', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    console.log(res)
    if (res.code === 200) {
      return res.data
    } else {
      // 处理业务错误
      ElMessage.error(res.message || '请求失败')
      return Promise.reject(new Error(res.message || '请求失败'))
    }
  },
  error => {
    // 处理 HTTP 错误状态
    let message = '请求失败'
    if (error.response) {
      switch (error.response.status) {
        case 400:
          message = '参数错误'
          break
        case 404:
          message = '请求错误，未找到该资源'
          break
        case 405:
          message = '请求方法不允许'
          break
        case 500:
          message = '服务器错误'
          break
        default:
          message = `请求失败: ${error.response.status}`
      }
    } else if (error.request) {
      message = '服务器未响应'
    }
    ElMessage.error(message)
    return Promise.reject(error)
  }
)

// 封装 GET 请求
export function get(url, params, config = {}) {
  return service({
    url,
    method: 'get',
    params,
    ...config
  })
}

// 封装 POST 请求
export function post(url, data, config = {}) {
  return service({
    url,
    method: 'post',
    data,
    ...config
  })
}

// 封装 PUT 请求
export function put(url, data, config = {}) {
  return service({
    url,
    method: 'put',
    data,
    ...config
  })
}

// 封装 DELETE 请求
export function del(url, params, config = {}) {
  return service({
    url,
    method: 'delete',
    params,
    ...config
  })
}

// 导出 axios 实例
export default service